"""
Copyright (c) 2023 - present SKbioinfo
"""
from flask_restful import Resource
from flask import request,jsonify,current_app
from apps.API.utils.log_helper import lg
from apps.API.connector.db_common import *
from apps.API.common.common_time import *
from apps.API.common.db_table_config import *
from flask_jwt_extended import jwt_required
from apps.API.pipeExecutor.models import Analysis
import os

"""URL:/api/pipeMonitor/PipeExecutorLog"""
class interfacePipeExecutorLog(Resource):
    @jwt_required()
    def post(self,id):
        """添加新用户到系统
        参数:
            id (str): 用户唯一ID
        返回:
            User: 创建的用户对象
        异常:
            ValueError: 如果用户已存在
        """
        try:
            baseDir=current_app.config.get("BASE_DIR")
            type=request.json["type"]
            trace_file_path = f'''{baseDir}/run/{type}/{id}/run_newstandard/pipeline_info/execution_trace_*txt'''
            trace_file_list = list(os.popen('ls -lt {trace_file_path}'.format(trace_file_path=trace_file_path)))
            trace_file = [ file for file in trace_file_list ][0].split()[-1].rstrip()
            content=[]
            if os.path.exists(trace_file):
                with open(trace_file,"r") as f:
                    next(f)
                    for line in f.readlines():
                        tmp=line.rstrip().split('\t')
                        # tmp_name = tmp[3]
                        content.append({
                            "task_id":tmp[0],
                            "hash":tmp[1],
                            "native_id":tmp[2],
                            "name":tmp[3],
                            "status":tmp[4],
                            "exit":tmp[5],
                            "submit":tmp[6],
                            "duration":tmp[7],
                            "realtime":tmp[8],
                            "%cpu":tmp[9],
                            "peak_rss":tmp[10],
                            "peak_vmem":tmp[11],
                            "rchar":tmp[12],
                            "wchar":tmp[13]
                        })
                response=jsonify(content)
                response.status=202
                return response
            else:
                return 300
        except Exception as e:
            lg.error(e)
            return 404

class interfaceFecthAnalysisInfo(Resource):
    @jwt_required()
    def get(self):
        try:
            username=request.args.get('username')
            page=int(request.args.get('page'))
            limit=int(request.args.get('limit'))
            query=Analysis.query.order_by(Analysis.run_id.desc())
            if username not in ['admin']:
                query=query.filter(Analysis.username==username)
            total_length=query.count()
            pagination=query.paginate(page=page, per_page=limit, error_out=False)
            results=[item.to_dict() for item in pagination.items]
            response=jsonify({"total":total_length,"data":results})
            response.status=202
            return response
        except Exception as e:
            lg.error(e)
            response=jsonify({})
            response.status=404
            return response
        
